﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using TyMES.Model;
using TyMES.ViewModel.Record.TrayBindVSNVMs;
using Elsa.Server.Api.Endpoints.WorkflowDefinitions;
using Newtonsoft.Json;
using System.Threading.Tasks;
using TyMES.Communication;
using TyMES.Model.Record;
using TyMES.PassStationCommunication;
using TyMES.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TyMES.TemporaryClass;
using TyMES.Model.BaseInformation;


namespace TyMES.Record.Controllers
{
    [AuthorizeJwtWithCookie]
    public partial class TrayBindVSNController : BaseApiController
    {
        private readonly ILogger<NormalPassStationDomain> _logger;
        private readonly IConfiguration _configuration;
        private readonly HttpService _httpService;
        private readonly IServiceScope _serviceScope;
        private readonly WTMContext _context;
        private readonly object lockobj;
        private string _LineCode;
        private string factoryCode;
        private string mesIP;
        private string mesPort;

        public TrayBindVSNController(ILogger<NormalPassStationDomain> logger, IConfiguration configuration, HttpService httpService,IServiceScopeFactory serviceScopeFactory)
        {
            _logger = logger;
            _configuration = configuration;
            _httpService = httpService;
            _serviceScope = serviceScopeFactory.CreateScope();
            var sp = _serviceScope.ServiceProvider;
            _context = sp.GetRequiredService<WTMContext>();
            this.factoryCode = configuration["FactoryCode"];
            this.mesIP = configuration["MESIP"];
            this.mesPort = configuration["MESPORT"];
            _LineCode = configuration["LineCode"];
        }

        [ActionDescription("Sys.Search")]
        [HttpPost("[action]")]
        public IActionResult SearchTrayBindVSN(TyMES.ViewModel.Record.TrayBindVSNVMs.TrayBindVSNSearcher searcher)
        {
            if (ModelState.IsValid)
            {
                var vm = Wtm.CreateVM<TyMES.ViewModel.Record.TrayBindVSNVMs.TrayBindVSNListVM>();
                vm.Searcher = searcher;
                return Content(vm.GetJson());
            }
            else
            {
                return BadRequest(ModelState.GetErrorJson());
            }
        }

        [ActionDescription("Sys.Export")]
        [HttpPost("[action]")]
        public IActionResult TrayBindVSNExportExcel(TyMES.ViewModel.Record.TrayBindVSNVMs.TrayBindVSNSearcher searcher)
        {
            var vm = Wtm.CreateVM<TyMES.ViewModel.Record.TrayBindVSNVMs.TrayBindVSNListVM>();
            vm.Searcher = searcher;
            vm.SearcherMode = ListVMSearchModeEnum.Export;
            return vm.GetExportData();
        }

        [ActionDescription("Sys.CheckExport")]
        [HttpPost("[action]")]
        public IActionResult TrayBindVSNExportExcelByIds(string[] ids)
        {
            var vm = Wtm.CreateVM<TyMES.ViewModel.Record.TrayBindVSNVMs.TrayBindVSNListVM>();
            if (ids != null && ids.Count() > 0)
            {
                vm.Ids = new List<string>(ids);
                vm.SearcherMode = ListVMSearchModeEnum.CheckExport;
            }
            return vm.GetExportData();
        }

        public record ParaShopCode(string TrayCode, string barcodeCategory, string stationCode);
        [ActionDescription("获取出货条码")]
        [HttpPost("GetShopCode")]
        public async Task<TrayBVSNResponse> GetShopCode(ParaShopCode para)
        {
            string url = "http://" + mesIP + ":" + mesPort + "/api/base/Base_Information";
            ResquestBody resquestBody = new ResquestBody
            {
                factoryCode = factoryCode,
                serviceId = "Product001_SNCreate",
                requestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                data = new List<TSdata>()
            };
            TSdata tsdata = new TSdata();
            var TrayInfo = DC.Set<TrayBindVSN>().Where(x => x.TrayCode == para.TrayCode && x.BindStatus == TrayBindStatusEnum.BIND).ToList();
            if (TrayInfo.Count == 1)
            {
                //正常的
                string thisOrderCode = TrayInfo[0].OrderCode;
                var orderInfo = DC.Set<Order_Model>().Where(x => x.OrderCode == thisOrderCode).ToList();

                tsdata.lineCode = _LineCode;
                tsdata.orderCode = thisOrderCode;
                tsdata.scheduleCode = orderInfo[0].ScheduleCode;
                tsdata.barcodeCategory = para.barcodeCategory;
                tsdata.snQty = "1";
                tsdata.stationCode = para.stationCode;
                resquestBody.data.Add(tsdata);
                try
                {
                    string psd = JsonConvert.SerializeObject(resquestBody);
                    string value = await _httpService.PostDataAsync(url, psd);
                    VSNRes vsnres = new VSNRes();
                    vsnres.data = new List<VSNdata>();
                    vsnres = JsonConvert.DeserializeObject<VSNRes>(value);
                    if (vsnres != null && vsnres.code == "000000")
                    {
                        return new TrayBVSNResponse("000000", true, false, vsnres.data[0].snBarcode, "", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    else
                    {
                        return new TrayBVSNResponse("000001", true, false, "", "未返回snnumber", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                }
                catch (Exception ex)
                {
                    return new TrayBVSNResponse("000002", true, false, "", "snnumber申请接口调用错误", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }

            }
            else if (TrayInfo.Count > 1)
            {
                //此托盘有不止一个处于OUT状态的sn号
                return new TrayBVSNResponse("000003", true, false, "", "此托盘有不止一个处于OUT状态的sn号", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }
            else
            {
                //报错此托盘没有绑定sn
                return new TrayBVSNResponse("000004", true, false, "", "报错此托盘没有绑定sn", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            }


        }
        public class ResquestBody {
            public string factoryCode { get; set; }
            public string serviceId {get; set; }
            public string requestTime { get; set; }
            public List<TSdata>  data {get;set;}
        };

    }
}


